package com.rem.spring.jdbc;

import com.rem.spring.annotionTx.config.Config;
import com.rem.spring.entity.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import java.util.List;

/**
 * @author Rem
 * @date 2023-03-06
 */
@SpringJUnitConfig(classes = Config.class)
public class JdbcTemplateTest {

    @Autowired
    JdbcTemplate jdbcTemplate;


    /**
     * 返回一个对象
     */
    @Test
    public void testSelect() {
        String sql = "select * from t_emp where id = ?";
        Emp emp = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Emp.class), 1);
        System.out.println(emp);
    }

    /**
     * 查询一个集合
     */
    @Test
    public void testSelectList() {
        String sql = "select * from t_emp";
        List<Emp> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
        System.out.println(list);
    }

    /**
     * 返回单个值
     */
    @Test
    public void testSelectValue() {
        String sql = "select count(*) from t_emp";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(count);
    }

    /**
     * 修改
     */
    @Test
    public void testUpdate() {
        String sql = "update t_emp set name= ? where id= ?";
        int rows = jdbcTemplate.update(sql, "kk", 1);
        System.out.println(rows);
    }

    /**
     * 添加
     */
    @Test
    public void testAdd() {
        String sql = "insert into t_emp values(NULL, ?, ?, ?)";
        int rows = jdbcTemplate.update(sql, "zhangsan", 20, "女");
        System.out.println(rows);
    }

    /**
     * 删除
     */
    @Test
    public void testDelete() {
        String sql = "delete from t_emp where id= ?";
        int rows = jdbcTemplate.update(sql, 4);
        System.out.println(rows);
    }
}
